package com.project.slsx.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.project.slsx.R;
import com.project.slsx.Constant.Constans;
import com.project.slsx.bean.LoginBean;
import com.project.slsx.bean.SwitchBean;
import com.project.slsx.bean.UsersBean;
import com.project.slsx.utils.DialogUtils;
import com.project.slsx.utils.ParamsUtils;
import com.project.slsx.utils.SPUtils;
import com.project.slsx.utils.UserManager;
import com.project.slsx.widget.dialog.BaseNiceDialog;
import com.project.slsx.widget.dialog.ViewConvertListener;
import com.project.slsx.widget.dialog.ViewHolder;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = LoginActivity.class.getSimpleName();
    private EditText edUsername;
    private EditText edPsd;
    private Button login;

    private String username;
    private String psd;
    private String tvSwitchMoney = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        edUsername = findViewById(R.id.ed_username);
        edPsd = findViewById(R.id.ed_psd);
        login = findViewById(R.id.btn_login);
        edUsername.addTextChangedListener(new UserNameWatcher());
        edPsd.addTextChangedListener(new PsdWatcher());
        login.setOnClickListener(this);
    }

    @Override
    public void initData() {

    }

    public void doLogin(View view) {
        startActivity(new Intent(mContext, CashRegisterActivity.class));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.btn_login:
                if (TextUtils.isEmpty(username)) {
                    showToast(mContext, "请输入用户名");
                    return;
                }

                if (TextUtils.isEmpty(psd)) {
                    showToast(mContext, "请输入密码");
                    return;
                }

                goLogin(username, psd);
                break;

            default:

                break;
        }
    }

    /**
     * 登录
     *
     * @param username
     * @param psd      18782010604
     *                 a12345678
     */
    private void goLogin(final String username, final String psd) {
        HttpParams hp = new HttpParams();
        hp.put("op", "userlogin");
//        hp.put("mobile", username);
//        hp.put("password",psd);

        hp.put("mobile", username);
        hp.put("password", psd);

        OkGo.<String>post(Constans.BASEURL).tag("login").isMultipart(true).params(hp).execute(new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                DialogUtils.showLoading(getSupportFragmentManager());
            }

            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: ");
                String body = response.body();
                LoginBean loginBean = JSONObject.parseObject(body, LoginBean.class);
                if (loginBean.getErrno() == Constans.SUCCESS) {
                    showToast(mContext, "登录成功!");
                    saveCurrentUser(username, psd, loginBean);
                    boolean isSwitch = SPUtils.getInstance().getBoolean(Constans.SWITCH, false);
                    if (isSwitch) {
                        DialogUtils.showDialog(R.layout.dialog_switch, 300, 240, true, switchListener, getSupportFragmentManager());
                    } else {
                        go2Main();
                    }
                } else {
                    showToast(mContext, loginBean.getErrmsg());
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Log.i(TAG, "onError: " + response.body());
                showToast(mContext, "网络错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                Log.i(TAG, "onFinish: ");
                DialogUtils.dissmissDialog();
            }
        });
    }


    private void saveCurrentUser(String username, String psd, LoginBean loginBean) {
        String userStr = SPUtils.getInstance().getString(Constans.USERS);

        UsersBean currentUser = new UsersBean();
        currentUser.setUsername(username);
        currentUser.setPsd(psd);
        currentUser.setToken(loginBean.getResult().getToken());
        currentUser.setUniacid(loginBean.getResult().getUniacid());
        currentUser.setSid(loginBean.getResult().getSid());

        UserManager.saveUser(JSONObject.toJSONString(currentUser));
        Log.i(TAG, "saveCurrentUser: " + UserManager.getUser().toString());

    }

    private void go2Main() {
        startActivity(new Intent(mContext, CashRegisterActivity.class));
        finish();
    }

    private ViewConvertListener switchListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            LinearLayout convertView = (LinearLayout) holder.getConvertView();
            EditText edSwitchMoney = convertView.findViewById(R.id.ed_switch_money);
            edSwitchMoney.addTextChangedListener(new MyWatcher());

            convertView.findViewById(R.id.btn_switch_ok).setOnClickListener(v -> {
                if (TextUtils.isEmpty(tvSwitchMoney)) {
                    showToast(mContext, "请输入金额");
                    return;
                }
                HttpParams shiftParams = ParamsUtils.getShiftParams();
                shiftParams.put("money", tvSwitchMoney);
                doShift(shiftParams);
            });

            convertView.findViewById(R.id.btn_switch_cancel).setOnClickListener(v -> {
                DialogUtils.dissmissDialog();
            });
        }
    };

    /**
     * 交班
     *
     * @param shiftParams
     */
    private void doShift(HttpParams shiftParams) {
        OkGo.<String>post(Constans.BASEURL).tag("shift").params(shiftParams).execute(new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
            }

            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
                SwitchBean switchBean = JSONObject.parseObject(response.body(), SwitchBean.class);
                showToast(mContext, switchBean.getErrmsg());
                tvSwitchMoney = "";

                if (switchBean.getErrno() == Constans.SUCCESS) {
                    SPUtils.getInstance().put(Constans.SWITCH, false);
                    go2Main();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                showToast(mContext, "网络错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUtils.dissmissDialog();
            }
        });
    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            tvSwitchMoney = s.toString().trim();
        }
    }

    private class UserNameWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            username = s.toString().trim();
        }
    }

    private class PsdWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            psd = s.toString().trim();
        }
    }
}
